﻿using System;
using Cubicle.Core.Shared;
using Cubicle.Nuget.Config;
using Cubicle.Nuget.Core;
using Cubicle.Nuget.Functions;
using ExcelDna.Integration;

namespace Cubicle.Nuget.Addin
{

    public class NugetAddIn : IExcelAddIn
    {
        // Nlog
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        //public NugetAddIn()
        //{
        //    // This must happen first for logging to work
        //    ExcelAsyncUtil.Initialize();
        //    _logger.Info("Registered Synchronization manager.");
        //}

        #region Implementation of IExcelAddIn

        public void AutoOpen()
        {
            try
            {
                _logger.Info(() => "Starting Nuget Add-In");
                var container = ContainerServices.CreateContainer();
                _logger.Info("Created Container.");
                var config = container.GetExportedValue<NugetConfig>();
                
                var feedManager = container.GetExportedValue<ClientManager>();
                _logger.Info("Created Feed-Manager.");

                NugetFunctions.Init(feedManager);
                _logger.Info("Initialised NugetFunctions.");

                // Auto update all
                if (config.AutoUpdate.Get<bool>()) 
                    NugetFunctions.AutoUpdateAll();

                _logger.Info(() => "Finished loading Nuget Add-In");                
            } catch (Exception e)
            {
                _logger.FatalException("Could not complete load for Nuget Add-In", e);
            }
        }

        public void AutoClose() { }

        #endregion

    }
}
